package com.rapig.mail.biz;

import java.util.ArrayList;
import java.util.List;
import java.util.Properties;

import javax.mail.Folder;
import javax.mail.Message;
import javax.mail.Session;
import javax.mail.Store;

import com.rapig.mail.bean.MailAccount;

public class MailBIZ {

	public static List<MailAccount> accounts = new ArrayList<MailAccount>();

	public static int getUnread() {
		if (accounts == null || accounts.size() <= 0) {
			return 0;
		}

		int total = 0;
		for (MailAccount item : accounts) {
			if (item == null) {
				continue;
			}
			Integer num = item.getNumUnread();
			if (num == null) {
				continue;
			}
			total = total + num;
		}
		return total;
	}

	public static MailAccount brief(MailAccount account) {
		try {
			Properties props = System.getProperties();
			props.setProperty("mail.store.protocol", account.getProtocol());
			props.setProperty("mail.imap.auth.login.disable",
					account.getPropAuthLogin());

			Session session = Session.getDefaultInstance(props, null);
			Store store = session.getStore(account.getProtocol());
			store.connect(account.getServer(), account.getUsername(),
					account.getPassword());

			Folder inbox = store.getFolder("Inbox");
			inbox.open(Folder.READ_ONLY);
			account.setNumUnread(inbox.getUnreadMessageCount());
			account.setNumNew(inbox.getNewMessageCount());
			account.setNumTotal(inbox.getMessageCount());

		} catch (Exception ex) {
			ex.printStackTrace();
		}
		return account;
	}

	public static Message[] list(MailAccount account, int page, int pageSize) {
		try {
			Properties props = System.getProperties();
			props.setProperty("mail.store.protocol", account.getProtocol());
			props.setProperty("mail.imap.auth.login.disable",
					account.getPropAuthLogin());

			Session session = Session.getDefaultInstance(props, null);
			Store store = session.getStore(account.getProtocol());
			store.connect(account.getServer(), account.getUsername(),
					account.getPassword());

			Folder inbox = store.getFolder("Inbox");
			inbox.open(Folder.READ_ONLY);
			account.setNumUnread(inbox.getUnreadMessageCount());
			account.setNumNew(inbox.getNewMessageCount());
			account.setNumTotal(inbox.getMessageCount());

			Message[] messages = inbox.getMessages(account.getNumTotal()
					- pageSize + (page - 1) * pageSize, account.getNumTotal()
					+ (page - 1) * pageSize);
			return messages;

		} catch (Exception ex) {

		}
		return null;
	}
}
